﻿using DongFangGuoKai.WMSPlatform.Commn.ExtendModule;
using DongFangGuoKai.WMSPlatform.Core.Repository;
using DongFangGuoKai.WMSPlatform.Domain.Enums;
using DongFangGuoKai.WMSPlatform.Domain.Models;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Concurrent;
namespace DongFangGuoKai.WMS.NodeBussiness
{
    public abstract class NodeBaseBusiness
    {
        public EmWorkDeviceType WorkDeviceType { get; protected set; }
        public EmInstructType InstructType { get; protected set; }
        public EmDeviceAction DeviceAction { get; protected set; }
     

        protected NodeBaseBusiness(IServiceProvider serviceProvider)
        {

            ServiceProvider = serviceProvider;  
        }
        public IServiceProvider  ServiceProvider { get;  }
        protected readonly static object _lockObj = new object();
        private static ConcurrentDictionary<string, bool> _lockDic = new ConcurrentDictionary<string, bool>();

        //接口方法
        private bool InterfaceExecStart(TInterfaceLog log, string businessClassName)
        {
            try
            {
                if (log == null || log.Id <= 0)
                {
                    return false;
                }
              
                var interfaceLogRepo = ServiceProvider.GetRequiredService<IRepository<TInterfaceLog>>();


                DateTime now = DateTime.Now;
                log.ExecDate = now;
                TInterfaceLog modifyLog = interfaceLogRepo.Get(x => x.Id == log.Id);
                if (modifyLog != null)
                {
                    modifyLog.Id = log.Id;
                    modifyLog.ExecDate = now;
                    modifyLog.ExecBusinessCalss = businessClassName;
                    modifyLog.ErrorMsg = log.ErrorMsg;


                    if (log.Status == 2)
                    {
                        modifyLog.Status = 2;
                    }
                    bool result = interfaceLogRepo.Update(modifyLog);
                    return result;

                }

                return false;

            }
            catch (Exception ex)
            {

                return false;
            }

        }
        private bool InterfaceExecFinished(TInterfaceLog log, int status, int taskId, int instructId, string errorMsg = "", string outParam = "")
        {
            try
            {
                if (log == null || log.Id <= 0)
                {
                    return false;
                }

                var interfaceLogRepo = ServiceProvider.GetRequiredService<IRepository<TInterfaceLog>>();

                DateTime now = DateTime.Now;
                DateTime execDate = log.ExecDate.GetValueOrDefault();
                int totalMilliseconds = (int)now.Subtract(execDate).TotalMilliseconds;
                TInterfaceLog modifyLog = interfaceLogRepo.Get(x => x.Id == log.Id);
                if (modifyLog != null)
                {
                    modifyLog.Id = log.Id;
                    modifyLog.FinishedDate = now;
                    modifyLog.ExecMillisecond = totalMilliseconds;
                    modifyLog.Status = status;
                    modifyLog.RefTaskId = taskId;
                    modifyLog.RefInstructId = instructId;
                    modifyLog.OutParam = outParam; 

                    if (log.Status == 2)
                    {
                        modifyLog.Status = 2;
                    }
                    bool result = interfaceLogRepo.Update(modifyLog);
                    return result;

                }

                return false;

            }
            catch (Exception ex)
            {

                return false;
            }

        }

        //通用逻辑
        public bool CmdStart(TInterfaceLog interfaceLog, out string msg, params object[] data)
        {
            msg = "";
            bool result = true;
            int taskId = 0;
            int instructId = 0;

            try
            {
                string businessClassName = this.GetType().Name;
                //处理公共方法
                InterfaceExecStart(interfaceLog, businessClassName);

                //业务执行开始
                result = ExecCreateInstruct(out msg, data);

                //业务执行结束
                return result;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return false;
            }
            finally
            {
                int status = 1;
                if (interfaceLog != null)
                {
                    if (interfaceLog.Status == 2)
                    {
                        status = 2;
                        if (!interfaceLog.ErrorMsg.IsNullOrEmpty())
                        {
                            msg = null;
                        }
                    }
                    else
                    {
                        status = result ? 1 : 3;
                    }
                }
                InterfaceExecFinished(interfaceLog, status, taskId, instructId, msg);
            }
        }
        public bool CmdFinished(TInterfaceLog interfaceLog, TInstruct instruct, out string msg)
        {
            msg = string.Empty;
            bool result = false;

            string key = "";
            int instructId = instruct.Id;
            if (instruct.Id <= 0)
            {
                msg = "参数错误,Id为空";
                return false;
            }
            if (instruct == null || instruct.ExpectedToLocation.IsNullOrEmpty())
            {
                msg = "参数错误";
                return false;
            }

            try
            {
                string businessClassName = this.GetType().Name;
                InterfaceExecStart(interfaceLog, businessClassName);
                key = this.GetType().Name + "_Finished_" + (string.IsNullOrEmpty(instruct.PalletBarcode) ? "" : instruct.PalletBarcode);

                //业务执行开始
                result = ExecInstructFinished(instruct, out msg);

                //业务执行结束
                return result;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return false;
            }
            finally
            {
                if (interfaceLog != null)
                {
                    interfaceLog.Status = result ? 1 : 3;
                }
                InterfaceExecFinished(interfaceLog, result ? 1 : 3, 0, instructId, msg);
            }


        }

        //业务执行
        protected abstract bool ExecCreateInstruct(out string msg, params object[] data);
        protected abstract bool ExecInstructFinished(TInstruct instruct, out string msg);

    }
}
